﻿using System.Threading.Tasks;
using Senparc.WebSocket.SignalR;

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Newtonsoft.Json;
using Entity.Project;
using NetCoreAPI.Socket;
using Commons;

namespace NetCoreAPI
{
    public class YvanHub : SenparcWebSocketHubBase
    {
        /// <summary>
        /// 重写Hub连接事件
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            return base.OnConnectedAsync();
        }
        
        //重写Hub链接断开事件
        public override Task OnDisconnectedAsync(Exception exception)
        {
            ////移出房间
            //for (int i = 0; i < SocketHelp.Rooms.Count; i++)
            //{
            //    if (SocketHelp.Rooms[i].Users.Exists(x=>x.ConnectionId==Context.ConnectionId))
            //    {
            //        int index = SocketHelp.Rooms[i].Users.FindIndex(x => x.ConnectionId == Context.ConnectionId);
            //        //SocketHelp.Rooms[i].Users.RemoveAt(index);
            //        SocketHelp.Rooms[i].Users[index].IsConnection = false;//标识断线
            //        Groups.RemoveFromGroupAsync(Context.ConnectionId, SocketHelp.Rooms[i].RoomKey);
            //        try
            //        {
            //            IsCurrentUser(i, index);
            //        }
            //        catch (Exception ex)
            //        {
            //            var log = new LogHelper<YvanHub>();
            //            log.Error(ex.Message);
            //        }
            //    }
            //}
            return base.OnDisconnectedAsync(exception);
        }
        
        /// <summary>
        /// 判断掉线的人在当前房间是否正在操作中
        /// 正在操作者默认弃牌
        /// </summary>
        /// <param name="roomIndex"></param>
        /// <param name="userIndex"></param>
        private void IsCurrentUser(int roomIndex,int userIndex)
        {
            //var room = SocketHelp.Rooms[roomIndex];
            //var user = room.Users[userIndex];
            //if (room.IsStarting==true && room.CurrentUserId==user.UserId)
            //{
            //    ResultData resultData = new ResultData() { Operation = UserOperation.Result, UserToken = user.UserToken };
            //    SocketHelp.Rooms[roomIndex].Users[userIndex].IsFold = true;
            //    RoomHelper.Next(roomIndex, user.UserToken);
            //    resultData.IsSuccess = true;
            //    resultData.Message = "OK";
            //    resultData.Room = SocketHelp.Rooms[roomIndex];
            //    object result = new
            //    {
            //        content = resultData.ToJsonString(),
            //        time = DateTime.Now.ToLongString()
            //    };
            //    SendAsync(result.ToJsonString(), Clients.Group(room.RoomKey), default);
            //}
        }
    }
    
}

